document.addEventListener("DOMContentLoaded", () => {
    const fileInput = document.getElementById("fileInput");
    const uploadButton = document.getElementById("uploadButton");
    const progressFill = document.getElementById("progressFill");
    const uploadStatus = document.getElementById("uploadStatus");

    let file;

    // Enable the upload button when a file is selected
    fileInput.addEventListener("change", (event) => {
        file = event.target.files[0];
        uploadStatus.textContent = file ? `Ready to upload: ${file.name}` : "Select a file to start uploading...";
        uploadButton.disabled = !file;
    });

    // Handle the upload process
    uploadButton.addEventListener("click", async () => {
        if (!file) return;

        const chunkSize = 2 * 1024 * 1024; // 2MB
        const totalChunks = Math.ceil(file.size / chunkSize);
        const identifier = new Date().getTime(); // Unique file identifier

        uploadButton.disabled = true;
        uploadStatus.textContent = `Uploading ${file.name}...`;
        progressFill.style.width = "0";

        let uploadedChunks = 0;

        for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
            const start = chunkIndex * chunkSize;
            const end = Math.min(file.size, start + chunkSize);
            const chunk = file.slice(start, end);

            const formData = new FormData();
            formData.append("file", chunk);
            formData.append("chunkIndex", chunkIndex);
            formData.append("totalChunks", totalChunks);
            formData.append("identifier", identifier);

            try {
                await fetch('/upload/uploadChunk', {
                    method: 'POST',
                    body: formData,
                });
                uploadedChunks++;
                const progress = (uploadedChunks / totalChunks) * 100;
                progressFill.style.width = `${progress}%`;
            } catch (error) {
                uploadStatus.textContent = `Failed to upload chunk ${chunkIndex + 1}`;
                uploadButton.disabled = false;
                return;
            }
        }

        // Notify server to merge chunks
        try {
            const response = await fetch('/upload/mergeChunks', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    totalChunks: totalChunks,
                    identifier: identifier,
                    fileName: file.name
                }),
            });
            const result = await response.text();
            console.log(result)
            uploadStatus.textContent = result;
        } catch (error) {
            uploadStatus.textContent = "Failed to merge chunks.";
        }

        uploadButton.disabled = false;
    });
});
